package com.app.reportproblem;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.app.reportproblem.MyUI.KeyboardHelper;
import com.app.reportproblem.MyUI.MyClickAbleImageView;
import com.app.reportproblem.Utils.Common;
import com.app.reportproblem.Utils.DecodeUtils;
import com.app.reportproblem.Utils.GPSTracker;
import com.app.reportproblem.Utils.PreferenceHelper;
import com.app.reportproblem.httpclient.HttpClientHelper;
import com.app.reportproblem.httpclient.MyJsonHttpResponseHandler;
import com.google.android.gms.internal.el;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ReportProblemActivity extends Activity implements OnClickListener, OnTouchListener {

	Dialog dsuc, dA;
	MyClickAbleImageView btnSendReport;
	ImageButton btnBack;
	int categoryId;
	View main;
	EditText edtAddress, edtNotes;
	ImageView imgReport;

	ImageButton btnOnContact;

	MyClickAbleImageView btnChupanh, btnChonanh;
	private static final int PICK_PHOTO = 1;
	private static final int CAMERA_REQUEST = 2;
	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_take_photo.jpg";
	String file_path = "";
	File fc;
	PreferenceHelper preferenceHelper;

	GPSTracker gpsTracker;

	double mLatitude;
	double mLongitude;
	TextView btnReport;

	ProgressDialog progressDialog;
	Handler mHandler = new Handler();

	private Uri fileUri; // file url to store image/video
	// directory name to store captured images and videos
	private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

	Uri mCapturedImageURI;
	String selectedPath;

	int typeImage = 1;

	Runnable r = new Runnable() {

		@Override
		public void run() {
			closeActivityAnim();
		}
	};
	
	Runnable rThoat = new Runnable() {
		
		@Override
		public void run() {
			closeActivityAnim();
		}
	};

	ImageView actionbar;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheInMemory(false).cacheOnDisc(true)
			.bitmapConfig(Config.RGB_565).build();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report_problem_v2);

		main = (View) findViewById(R.id.main_problem);
		
		

		KeyboardHelper.setupUI(ReportProblemActivity.this, main);
		preferenceHelper = new PreferenceHelper(this);
		
		actionbar = (ImageView) findViewById(R.id.actionbar);
		ImageLoader.getInstance().displayImage(preferenceHelper.getUrlActionBar(), actionbar, options);
		categoryId = getIntent().getIntExtra("categoryId", 0);
		
		Log.i("DATA", ""+preferenceHelper.getUserId());

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnSendReport = (MyClickAbleImageView) findViewById(R.id.btn_sendproblem);
		edtNotes = (EditText) findViewById(R.id.edt_notes);
		btnChupanh = (MyClickAbleImageView) findViewById(R.id.btn_capture_imge);
		btnChonanh = (MyClickAbleImageView) findViewById(R.id.img_choose_image);
		imgReport = (ImageView) findViewById(R.id.imge_report);
		btnReport = (TextView) findViewById(R.id.btn_report);

		init();
		getLocation();
		edtNotes.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					KeyboardHelper.hideSoftKeyboard(ReportProblemActivity.this);
				}
				return false;
			}
		});

	}

	void getLocation() {
		gpsTracker = new GPSTracker(ReportProblemActivity.this);

		// check if GPS enabled
		if (gpsTracker.canGetLocation()) {

			mLatitude = gpsTracker.getLatitude();
			mLongitude = gpsTracker.getLongitude();
			Log.i("DATA", "" + mLatitude + " " + mLongitude);

			// \n is for new line
			// Toast.makeText(getApplicationContext(),
			// "Your Location is - \nLat: " + mLatitude + "\nLong: " +
			// mLongitude, Toast.LENGTH_LONG).show();
		} else {
			// can't get location
			// GPS or Network is not enabled
			// Ask user to enable GPS/network in settings
			gpsTracker.showSettingsAlert();
		}
	}

	void init() {
//		btnBack.setOnClickListener(this);
		btnBack.setOnTouchListener(this);
		btnSendReport.setOnTouchListener(this);
//		btnChupanh.setOnClickListener(this);
//		btnChonanh.setOnClickListener(this);
		btnChupanh.setOnTouchListener(this);
		btnChonanh.setOnTouchListener(this);
		btnReport.setOnTouchListener(this);
		
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		closeActivityAnim();
	}

	public void closeActivityAnim() {
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	void reportProblem() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							switch (status) {
							case 200:
								showDialogReportSuccess();
								break;
							case 400:
								Toast.makeText(ReportProblemActivity.this,
										getString(R.string.invalid),
										Toast.LENGTH_SHORT).show();
								break;
							case 404:
								Toast.makeText(ReportProblemActivity.this,
										getString(R.string.notfound),
										Toast.LENGTH_SHORT).show();
								break;
							case 500:
								Toast.makeText(ReportProblemActivity.this,
										getString(R.string.error),
										Toast.LENGTH_SHORT).show();
								break;
							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});
	}

	void showDialogReportSuccess() {
		dsuc = new Dialog(ReportProblemActivity.this);
		dsuc.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dsuc.setContentView(R.layout.dialog_report_success);

		Button btnOk = (Button) dsuc.findViewById(R.id.btnOk);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dsuc.dismiss();
				mHandler.postDelayed(r, 200);
			}
		});
		dsuc.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			closeActivityAnim();
			break;
		case R.id.btn_sendproblem:
			// reportProblem();
			if (!file_path.matches("")) {
				progressDialog = ProgressDialog.show(
						ReportProblemActivity.this, "", "Reporting...");
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (null != progressDialog
								&& progressDialog.isShowing())
							progressDialog.dismiss();
					}
				}, 90000);
				sendProblem();
			} else {
				Toast.makeText(ReportProblemActivity.this,
						"Field is not blank.", Toast.LENGTH_SHORT).show();
			}

			break;
		case R.id.btn_capture_imge:
			typeImage = 1;
			takeImage();
			break;
		case R.id.img_choose_image:
			typeImage = 2;
			openGallery();
			break;
		case R.id.btn_report:
			
			break;
		default:
			break;
		}
	}

	/* funtion pick image to gallery */
	public void openGallery() {
		File ff = new File(TEMP_TAKE_IMAGE);
		if (ff.exists())
			ff.delete();
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, PICK_PHOTO);
	}

	public void takeImage() {
		String fileName = "temp.jpg";
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.TITLE, fileName);
		mCapturedImageURI = getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
		startActivityForResult(intent, CAMERA_REQUEST);

	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if ((intent != null || requestCode == CAMERA_REQUEST)
				&& resultCode == RESULT_OK) {
			switch (requestCode) {
			case CAMERA_REQUEST:
				/*
				 * Bundle extras = intent.getExtras(); Bitmap imageBitmap =
				 * (Bitmap) extras.get("data");
				 * imgReport.setImageBitmap(imageBitmap);
				 */

				String[] projection = { MediaStore.Images.Media.DATA };
				Cursor cursor1 = managedQuery(mCapturedImageURI, projection,
						null, null, null);
				int column_index_data = cursor1
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor1.moveToFirst();
				file_path = cursor1.getString(column_index_data);
				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm1 = DecodeUtils.decode(ReportProblemActivity.this,
						Uri.parse(file_path), 300, 300);

				fc = new File(file_path);
				FileOutputStream fo;
				try {
					fo = new FileOutputStream(fc);
					bm1.compress(CompressFormat.JPEG, 90, fo);
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}

				imgReport.setScaleType(ScaleType.CENTER_CROP);
				imgReport.setImageBitmap(bm1);

				cursor1.close();

				break;
			case PICK_PHOTO:
				Uri u = (Uri) intent.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(u, filePathColumn,
						null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				file_path = cursor.getString(columnIndex);

				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm = DecodeUtils.decode(ReportProblemActivity.this,
						Uri.parse(file_path), 300, 300);

				fc = new File(file_path);
				FileOutputStream fo1;
				try {
					fo1 = new FileOutputStream(fc);
					bm.compress(CompressFormat.JPEG, 90, fo1);
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}

				if (bm == null) {
					Toast.makeText(ReportProblemActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}

				imgReport.setScaleType(ScaleType.CENTER_CROP);
				imgReport.setImageBitmap(bm);
				cursor.close();
				break;
			}
		}

	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	void sendProblem() {
		JSONObject data = new JSONObject();
		try {
			data.put("category_id", categoryId);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			data.put("lon", mLongitude);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			data.put("lat", mLatitude);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			data.put("note", edtNotes.getText().toString());
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		RequestParams params = new RequestParams();
		params.put("userId", String.valueOf(preferenceHelper.getUserId()));
		params.put("data", data.toString());
		try {
			params.put("fileUpload", fc);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://fl.jshort.vn/api/postProblem", params,
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						Toast.makeText(ReportProblemActivity.this,
								"Request failed.", Toast.LENGTH_SHORT).show();
						progressDialog.dismiss();
					}

					@Override
					public void onSuccess(JSONObject re) {
						progressDialog.dismiss();
						try {
							int status = re.getInt("status");
							switch (status) {
							case 200:
								showDialogReportSuccess();
								break;
							case 400:

								Toast.makeText(ReportProblemActivity.this,
										"Invalid Field.", Toast.LENGTH_SHORT)
										.show();
								break;
							case 404:
								Toast.makeText(ReportProblemActivity.this,
										"Not found.", Toast.LENGTH_SHORT)
										.show();
								break;

							case 500:
								Toast.makeText(ReportProblemActivity.this,
										"Server error.", Toast.LENGTH_SHORT)
										.show();
								break;

							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

				});

	}

	/**
	 * ------------ Helper Methods ----------------------
	 * */

	/**
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri() {
		return Uri.fromFile(getOutputMediaFile());
	}

	/**
	 * returning image / video
	 */
	private static File getOutputMediaFile() {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		mediaFile = new File(mediaStorageDir.getPath() + File.separator
				+ "IMG_" + timeStamp + ".jpg");

		return mediaFile;
	}
	
	void showDialogThoat() {
		dA = new Dialog(ReportProblemActivity.this);
		dA.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dA.setContentView(R.layout.dialog_thoat);

		Button btnOk = (Button) dA.findViewById(R.id.btnOk);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dA.dismiss();
				mHandler.postDelayed(rThoat,200);
			}
		});
		
		Button btnCancel = (Button) dA.findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				dA.dismiss();
			}
		});
		
		dA.show();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				showDialogThoat();
			}
			
			break;
		case R.id.btn_capture_imge:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				typeImage = 1;
				takeImage();
			}
			break;
		case R.id.img_choose_image:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				typeImage = 2;
				openGallery();
			}
			break;
		case R.id.btn_sendproblem:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				sendReportProblem();
			}
			break;
		case R.id.btn_report:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				sendReportProblem();
			}
			break;
		default:
			break;
		}
		return false;
	}
	
	void sendReportProblem() {
		if (!file_path.matches("")) {
			progressDialog = ProgressDialog.show(
					ReportProblemActivity.this, "", "Reporting...");
			sendProblem();
		} else {
			Toast.makeText(ReportProblemActivity.this,
					"Field is not blank.", Toast.LENGTH_SHORT).show();
		}
	}

}
